<template>
  <div id="app">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="logo">Gim-chat</div>
      <div class="top-nav"></div>
      <div class="user-info">
        <template v-if="isLogin">
          <img :src="userInfo.avatarUrl" alt="头像"
            style="width: 36px; height: 36px; border-radius: 50%; object-fit: cover;" />
          <span class="username">Hi, {{ userInfo.userName }}</span>
          <el-button type="danger" @click="doLogout" size="small">登出</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="doLogin" size="small">登录</el-button>
        </template>
      </div>
    </header>

    <!-- 页面主体 -->
    <div class="app-body">
      <!-- 左侧导航栏 -->
      <aside class="sidebar">
        <ul>
          <li><router-link to="/chat">💬 聊天</router-link></li>
          <li><router-link to="/group">🛠️ 工具</router-link></li>
          <li><router-link to="/docs">📄 文档</router-link></li>
           <li><router-link to="/aiVideoCreate">📄 AI视频制作</router-link></li>
          <li><router-link to="/newList">📰 新闻</router-link></li>
          <li><router-link to="/ai"><img src="@/assets/images/avatar/openai.svg" alt="AI Avatar" class="avatar-img"
                style="margin-right: 5px;" /> AI</router-link></li>
          <li><router-link to="/knowledge">📚 知识库</router-link></li>
          <li><router-link to="/setting">⚙️ 设置</router-link></li>
        </ul>
      </aside>

      <!-- 主内容区域 -->
      <main class="main-view">
        <router-view />
      </main>

      <!-- 修改右侧栏和按钮部分 -->
      <!-- <div class="toggle-rightbar-btn" @click="isRightbarCollapsed = !isRightbarCollapsed">
        <span v-if="isRightbarCollapsed">🤖</span>
        <span v-else style="color: #333333; font-weight: bold; font-size: 20px;">➤</span>
      </div>

      <transition name="slide-width">
        <aside class="rightbar" v-if="!isRightbarCollapsed">
          <p class="title">AI助手</p>
        </aside>
        <RightBar v-if="!isRightbarCollapsed" />
      </transition> -->
    </div>


    <el-dialog title="用户登录" :visible.sync="loginDialogVisible" width="400px" center :show-close="false"
      :close-on-click-modal="false" class="login-dialog">
      <el-card class="login-card">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px" label-position="top"
          class="login-form">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="loginForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="passWord">
            <el-input v-model="loginForm.passWord" type="password" show-password placeholder="请输入密码"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitLogin" style="width: 100%">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import RightBar from '@/components/RightBar.vue'
import { handleLogin, handleLogout } from '@/api/user'
import WebSocketService from '@/plugins/ws'; // ✅ 正确
import Vue from 'vue'

export default {
  components: { RightBar },
  data() {
    return {
      defaultAvatar: 'https://iknow-pic.cdn.bcebos.com/962bd40735fae6cd17bafbff1db30f2442a70f25',
      isRightbarCollapsed: true,
      loginDialogVisible: false,/// 登录对话框可见性
      loginForm: {
        phone: "",
        passWord: "",
      },
      loginRules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入合法的手机号",
            trigger: "blur",
          },
        ],
        passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  mounted() {
    // 监听浏览器关闭事件，清除登录状态
    window.addEventListener('beforeunload', this.clearLoginState);
  },
  beforeDestroy() {
    // 在组件销毁时移除事件监听，避免内存泄漏
    window.removeEventListener('beforeunload', this.clearLoginState);
  },
  computed: {
    isLogin() {
      return this.$store.getters['user/isLogin'];
    },
    userInfo() {
      return this.$store.state.user.userInfo || {}
    }
  },
  methods: {
    /**
     * 清除登录状态
     */
    // 清除登录状态
    clearLoginState() {
      if (performance.getEntriesByType('navigation')[0].type !== 'reload') {
        // 只有在关闭标签页或浏览器时清除登录状态
        this.$store.dispatch('user/logout'); // Vuex 中登出
      }
    },
    //用户登录表单提交
    async submitLogin() {

      const that = this
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // TODO: 提交登录逻辑
          const param = { ...this.loginForm }
          try {
            handleLogin(param).then(res => {

              const data = res.data.data;

              if (res.data.code === 200 && data.token) {
                const token = data.token;
                const user = data.userInfo;

                // 存入 Vuex
                that.$store.dispatch('user/login', {
                  token,
                  userInfo: user
                });

                that.loginDialogVisible = false;

                that.$message.success('登录成功');

                this.initWebSocket(user.userId)

              } else {
                that.loginDialogVisible = false;
                that.$message.error(res.data.message || '登录失败');
              }

            })

          } catch (e) {
            console.error(e);
            that.$message.error('网络错误或服务异常');
          }

        }
      });
    },
    /**
     * 登录预处理操作
     */
    async doLogin() {
      // 打开登录对话框
      this.loginDialogVisible = true;
    },
    /**
     * 用户登出
     */
    async doLogout() {
      // TODO: 登出逻辑

      const param = {
        userId: this.userInfo.userId
      }

      const res = await handleLogout(param)

      if (res && res.data && res.data.code === 200) {

        this.$store.dispatch('user/logout')

        this.$message.success('已登出');

        this.$router.push({
          name: 'ai'
        });

      } else {
        this.$message.error(res.data.message);
      }

    },
    /**
     * 初始化 AI Chat WebSocket
     * @param userId 
     */
    initWebSocket(userId) {
      if (this.wsService) {
        this.wsService.close();
      }
      this.wsService = new WebSocketService(this.$store);
      this.wsService.connect(userId);

      this.$ws = this.wsService; // 全局使用 $ws
      Vue.prototype.$ws = this.wsService;
      this.$ws.send({

      })
    },
    /**
     * 清空缓存
     */
    clearCache() {
      this.$store.dispatch('user/logout');
    }
  },

};
</script>

<style lang="less" scoped>
.user-info {
  display: flex;
  align-items: center;

  .avatar {
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .username {
    margin-right: 15px;
    font-size: 14px;
    line-height: 1;
    display: flex;
    align-items: center;
    height: 36px; // 与 avatar 大小一致
  }

  .el-button {
    margin-left: 5px;
  }
}

.login-dialog ::v-deep .el-dialog__body {
  padding: 0;
}

.login-card {
  border: none;
  box-shadow: none;
  padding: 30px 20px;
  background-color: #ffffff;
  border-radius: 8px;
}

.login-form {
  margin-top: 10px;
}

.el-dialog__header {
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}

.avatar-img {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: none;
  background: #fff;
}

#app {
  height: 97vh;
  display: flex;
  flex-direction: column;
  font-family: Avenir, Helvetica, Arial, sans-serif;
}

/* 顶部导航栏 */
.app-header {
  height: 60px;
  background: #2c3e50;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;

  .logo {
    font-weight: bold;
    font-size: 20px;
  }

  .top-nav a {
    margin: 0 10px;
    color: white;
    text-decoration: none;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}

/* 主体布局 */
.app-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧导航栏 */
/* 左侧导航栏 */
.sidebar {
  width: 150px;
  background: #ffffff;
  padding: 20px 10px;
  border-right: 1px solid #e6e6e6;
  box-shadow: 2px 0 6px rgba(0, 0, 0, 0.03);

  ul {
    list-style: none;
    padding: 0;
    margin: 0;

    li {
      margin-bottom: 12px;

      a {
        display: flex;
        align-items: center;
        padding: 10px 14px;
        font-size: 16px;
        color: #34495e;
        text-decoration: none;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          background-color: #f0f9ff;
          color: #1e90ff;
        }

        &.router-link-exact-active {
          background-color: #e6f7ff;
          color: #1890ff;
          font-weight: 600;
        }
      }
    }
  }
}

/* 主内容区域 */
.main-view {
  flex: 1;
  padding: 20px;
  background: #fff;
  overflow-y: auto;
}

/* 折叠按钮样式 */
.toggle-rightbar-btn {
  width: 30px;
  background: #f5f5f5;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
}

/* 动画 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter,
.slide-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

/* 右侧工具栏样式 */
.rightbar {
  width: 250px;
  background: #f0f2f5;
  padding: 10px;
  border-left: 1px solid #eee;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;

  .title {
    font-weight: bold;
    margin-bottom: 10px;
  }
}

/* 新增宽度动画 */
.slide-width-enter-active,
.slide-width-leave-active {
  transition: width 0.3s ease, opacity 0.3s ease;
  overflow: hidden;
  /* 确保动画过程中不显示溢出 */
}

.slide-width-enter-from,
.slide-width-leave-to {
  width: 0;
  opacity: 0;
}

.slide-width-enter-to,
.slide-width-leave-from {
  width: 250px;
  opacity: 1;
}

/* 调整折叠按钮样式，让按钮不被右侧栏遮挡 */
.toggle-rightbar-btn {
  width: 30px;
  background: #f5f5f5;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
  z-index: 10;
  position: relative;
  user-select: none;
}
</style>